#include "MainWindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QListWidget>
#include <QListWidgetItem>
#include <QTextEdit>
#include <QMessageBox>
#include <QTime>
#include <QFont>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_stackedWidget(nullptr)
    , m_sudokuBoard(nullptr)
    , m_levelManager(nullptr)
    , m_gameTimer(nullptr)
    , m_elapsedTime(0)
    , m_currentLevelId(1)
{
    setWindowTitle("数独游戏");
    setMinimumSize(600, 700);
    
    m_levelManager = new LevelManager(this);
    setupUI();
    
    // 连接游戏管理器信号
    connect(&GameManager::instance(), &GameManager::levelCompleted, 
            this, &MainWindow::showCongratulations);
}

MainWindow::~MainWindow()
{
}

void MainWindow::setupUI()
{
    m_stackedWidget = new QStackedWidget(this);
    setCentralWidget(m_stackedWidget);
    
    setupMainMenu();
    setupGameScreen();
    setupLevelSelectionScreen();
    setupProgressScreen();
    
    // 设置应用程序样式
    setStyleSheet(R"(
        QMainWindow {
            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                stop: 0 #667eea, stop: 1 #764ba2);
        }
        QWidget {
            background: transparent;
            font-family: 'Segoe UI', Arial, sans-serif;
        }
        QPushButton {
            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                stop: 0 #6a11cb, stop: 1 #2575fc);
            color: white;
            border: none;
            padding: 12px 24px;
            font-size: 16px;
            font-weight: bold;
            border-radius: 8px;
            min-width: 80px;
            min-height: 40px;
        }
        QPushButton:hover {
            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                stop: 0 #7e22ce, stop: 1 #3b82f6);
            transform: translateY(-1px);
        }
        QPushButton:pressed {
            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                stop: 0 #581c87, stop: 1 #1e40af);
        }
        QLabel {
            color: white;
            font-size: 16px;
            font-weight: bold;
            background: transparent;
        }
        QListWidget {
            background-color: rgba(255, 255, 255, 0.95);
            border: 2px solid #6a11cb;
            border-radius: 8px;
            font-size: 14px;
            color: #2c3e50;
        }
        QListWidget::item {
            padding: 12px;
            border-bottom: 1px solid #e0e0e0;
        }
        QListWidget::item:selected {
            background-color: #6a11cb;
            color: white;
        }
        QListWidget::item:hover {
            background-color: #f8f9fa;
        }
        QTextEdit {
            background-color: rgba(255, 255, 255, 0.95);
            border: 2px solid #6a11cb;
            border-radius: 8px;
            font-size: 14px;
            padding: 10px;
            color: #2c3e50;
        }
    )");
    
    m_stackedWidget->setCurrentWidget(m_mainMenuScreen);
}

void MainWindow::setupMainMenu()
{
    m_mainMenuScreen = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(m_mainMenuScreen);
    layout->setSpacing(20);
    layout->setContentsMargins(20, 20, 20, 20);
    
    // 标题
    QLabel *titleLabel = new QLabel("数独游戏");
    titleLabel->setAlignment(Qt::AlignCenter);
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(32);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    titleLabel->setStyleSheet("color: white; margin-bottom: 40px;");
    
    // 按钮
    m_newGameButton = new QPushButton("开始游戏");
    m_levelSelectButton = new QPushButton("选择关卡");
    m_progressButton = new QPushButton("游戏进度");
    m_quitButton = new QPushButton("退出游戏");
    
    layout->addStretch();
    layout->addWidget(titleLabel);
    layout->addStretch();
    layout->addWidget(m_newGameButton);
    layout->addWidget(m_levelSelectButton);
    layout->addWidget(m_progressButton);
    layout->addWidget(m_quitButton);
    layout->addStretch();
    
    connect(m_newGameButton, &QPushButton::clicked, this, &MainWindow::onNewGame);
    connect(m_levelSelectButton, &QPushButton::clicked, this, &MainWindow::onShowLevels);
    connect(m_progressButton, &QPushButton::clicked, this, &MainWindow::onShowProgress);
    connect(m_quitButton, &QPushButton::clicked, this, &QMainWindow::close);
    
    m_stackedWidget->addWidget(m_mainMenuScreen);
}

void MainWindow::setupGameScreen()
{
    m_gameScreen = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout(m_gameScreen);
    mainLayout->setSpacing(15);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    
    // 顶部信息栏
    QHBoxLayout *infoLayout = new QHBoxLayout();
    
    m_levelLabel = new QLabel("关卡: 1");
    m_difficultyLabel = new QLabel("难度: 简单");
    m_timerLabel = new QLabel("时间: 00:00");
    
    QFont infoFont = m_levelLabel->font();
    infoFont.setPointSize(14);
    infoFont.setBold(true);
    m_levelLabel->setFont(infoFont);
    m_difficultyLabel->setFont(infoFont);
    m_timerLabel->setFont(infoFont);
    
    infoLayout->addWidget(m_levelLabel);
    infoLayout->addWidget(m_difficultyLabel);
    infoLayout->addStretch();
    infoLayout->addWidget(m_timerLabel);
    
    // 数独棋盘
    m_sudokuBoard = new SudokuBoard();
    
    // 按钮栏
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    
    m_checkButton = new QPushButton("检查答案");
    m_resetButton = new QPushButton("重置棋盘");
    m_hintButton = new QPushButton("提示");
    m_menuButton = new QPushButton("返回菜单");
    
    buttonLayout->addWidget(m_checkButton);
    buttonLayout->addWidget(m_resetButton);
    buttonLayout->addWidget(m_hintButton);
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_menuButton);
    
    mainLayout->addLayout(infoLayout);
    mainLayout->addWidget(m_sudokuBoard, 1);
    mainLayout->addLayout(buttonLayout);
    
    // 连接信号
    connect(m_sudokuBoard, &SudokuBoard::puzzleSolved, this, &MainWindow::onPuzzleSolved);
    connect(m_sudokuBoard, &SudokuBoard::cellValueChanged, this, &MainWindow::onCellValueChanged);
    connect(m_checkButton, &QPushButton::clicked, this, &MainWindow::onCheckSolution);
    connect(m_resetButton, &QPushButton::clicked, this, &MainWindow::onResetBoard);
    connect(m_hintButton, &QPushButton::clicked, this, &MainWindow::onHintRequested);
    connect(m_menuButton, &QPushButton::clicked, this, &MainWindow::onShowMainMenu);
    
    // 初始化计时器
    m_gameTimer = new QTimer(this);
    connect(m_gameTimer, &QTimer::timeout, this, &MainWindow::onTimerTimeout);
    
    m_stackedWidget->addWidget(m_gameScreen);
}

void MainWindow::setupLevelSelectionScreen()
{
    m_levelScreen = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(m_levelScreen);
    layout->setSpacing(15);
    layout->setContentsMargins(30, 30, 30, 30);
    
    QLabel *titleLabel = new QLabel("选择关卡");
    titleLabel->setAlignment(Qt::AlignCenter);
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(24);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    
    m_levelList = new QListWidget();
    m_levelBackButton = new QPushButton("返回菜单");
    
    layout->addWidget(titleLabel);
    layout->addWidget(m_levelList, 1);
    layout->addWidget(m_levelBackButton);
    
    connect(m_levelList, &QListWidget::itemClicked, this, &MainWindow::onLevelItemClicked);
    connect(m_levelBackButton, &QPushButton::clicked, this, &MainWindow::onShowMainMenu);
    
    m_stackedWidget->addWidget(m_levelScreen);
}

void MainWindow::setupProgressScreen()
{
    m_progressScreen = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(m_progressScreen);
    layout->setSpacing(15);
    layout->setContentsMargins(30, 30, 30, 30);
    
    m_progressTitle = new QLabel("游戏进度");
    m_progressTitle->setAlignment(Qt::AlignCenter);
    QFont titleFont = m_progressTitle->font();
    titleFont.setPointSize(24);
    titleFont.setBold(true);
    m_progressTitle->setFont(titleFont);
    
    m_progressText = new QTextEdit();
    m_progressText->setReadOnly(true);
    
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    m_progressBackButton = new QPushButton("返回菜单");
    m_resetProgressButton = new QPushButton("重置进度");
    
    buttonLayout->addWidget(m_resetProgressButton);
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_progressBackButton);
    
    layout->addWidget(m_progressTitle);
    layout->addWidget(m_progressText, 1);
    layout->addLayout(buttonLayout);
    
    connect(m_progressBackButton, &QPushButton::clicked, this, &MainWindow::onShowMainMenu);
    connect(m_resetProgressButton, &QPushButton::clicked, this, [this]() {
        auto reply = QMessageBox::question(this, "重置进度", "确定要重置所有游戏进度吗？此操作不可撤销！");
        if (reply == QMessageBox::Yes) {
            GameManager::instance().resetProgress();
            onShowProgress(); // 刷新显示
        }
    });
    
    m_stackedWidget->addWidget(m_progressScreen);
}

void MainWindow::onNewGame()
{
    startGame(GameManager::instance().getProgress().currentLevel);
}

void MainWindow::onShowLevels()
{
    // 更新关卡列表
    m_levelList->clear();
    
    QVector<SudokuLevel> levels = m_levelManager->getAllLevels();
    for (const SudokuLevel &level : levels) {
        QString levelText = QString("%1: %2 (难度: %3)").arg(level.levelId).arg(level.name).arg(level.difficulty);
        
        // 添加完成状态
        if (GameManager::instance().isLevelCompleted(level.levelId)) {
            LevelProgress progress = GameManager::instance().getLevelProgress(level.levelId);
            levelText += QString(" ✓ 最佳: %1").arg(formatTime(progress.bestTime));
        }
        
        QListWidgetItem *item = new QListWidgetItem(levelText);
        item->setData(Qt::UserRole, level.levelId);
        m_levelList->addItem(item);
    }
    
    m_stackedWidget->setCurrentWidget(m_levelScreen);
}

void MainWindow::onShowProgress()
{
    GameProgress progress = GameManager::instance().getProgress();
    QString progressText;
    
    progressText += QString("当前关卡: %1\n\n").arg(progress.currentLevel);
    progressText += QString("已完成关卡: %1/%2\n\n").arg(GameManager::instance().getCompletedLevelCount()).arg(m_levelManager->getLevelCount());
    
    QVector<SudokuLevel> levels = m_levelManager->getAllLevels();
    for (const SudokuLevel &level : levels) {
        LevelProgress levelProgress = GameManager::instance().getLevelProgress(level.levelId);
        
        progressText += QString("关卡 %1: %2\n").arg(level.levelId).arg(level.name);
        if (levelProgress.completed) {
            progressText += QString("  状态: 已完成\n");
            progressText += QString("  完成时间: %1\n").arg(levelProgress.completionTime.toString("yyyy-MM-dd hh:mm"));
            progressText += QString("  尝试次数: %1\n").arg(levelProgress.attempts);
            progressText += QString("  最佳时间: %1\n").arg(formatTime(levelProgress.bestTime));
        } else {
            progressText += QString("  状态: 未完成\n");
            progressText += QString("  尝试次数: %1\n").arg(levelProgress.attempts);
        }
        progressText += "\n";
    }
    
    m_progressText->setText(progressText);
    m_stackedWidget->setCurrentWidget(m_progressScreen);
}

void MainWindow::onShowMainMenu()
{
    if (m_gameTimer && m_gameTimer->isActive()) {
        m_gameTimer->stop();
    }
    m_stackedWidget->setCurrentWidget(m_mainMenuScreen);
}

void MainWindow::onLevelItemClicked(QListWidgetItem *item)
{
    int levelId = item->data(Qt::UserRole).toInt();
    startGame(levelId);
}

void MainWindow::startGame(int levelId)
{
    SudokuLevel level = m_levelManager->getLevel(levelId);
    if (level.puzzle.isEmpty()) {
        QMessageBox::warning(this, "错误", "选择的关卡不存在！");
        return;
    }
    
    m_currentLevelId = levelId;
    m_elapsedTime = 0;
    
    // 更新界面信息
    m_levelLabel->setText(QString("关卡: %1").arg(level.levelId));
    
    QString difficultyText;
    switch(level.difficulty) {
        case 1: difficultyText = "简单"; break;
        case 2: difficultyText = "中等"; break;
        case 3: difficultyText = "困难"; break;
        case 4: difficultyText = "专家"; break;
        case 5: difficultyText = "大师"; break;
        default: difficultyText = "未知";
    }
    m_difficultyLabel->setText(QString("难度: %1").arg(difficultyText));
    
    updateTimerDisplay();
    
    // 初始化棋盘
    m_sudokuBoard->initializeBoard(level.puzzle, level.solution);
    m_sudokuBoard->setLevelDifficulty(level.difficulty);
    
    // 开始计时
    m_gameTimer->start(1000);
    
    // 记录游戏开始
    GameManager::instance().levelAttempted(levelId);
    GameManager::instance().setCurrentLevel(levelId);
    
    m_stackedWidget->setCurrentWidget(m_gameScreen);
}

void MainWindow::onPuzzleSolved()
{
    m_gameTimer->stop();
    GameManager::instance().levelCompleted(m_currentLevelId, m_elapsedTime);
}

void MainWindow::onCellValueChanged(int row, int col, int value)
{
    // 可以在这里添加音效或其他反馈
    Q_UNUSED(row);
    Q_UNUSED(col);
    Q_UNUSED(value);
}

void MainWindow::onTimerTimeout()
{
    m_elapsedTime++;
    updateTimerDisplay();
}

void MainWindow::onCheckSolution()
{
    if (m_sudokuBoard->checkSolution()) {
        QMessageBox::information(this, "恭喜", "答案正确！");
        onPuzzleSolved();
    } else {
        QMessageBox::warning(this, "提示", "答案不正确，请继续努力！");
    }
}

void MainWindow::onResetBoard()
{
    m_sudokuBoard->resetBoard();
    m_elapsedTime = 0;
    updateTimerDisplay();
    m_gameTimer->start(1000);
}

void MainWindow::onHintRequested()
{
    QMessageBox::information(this, "提示", "尝试检查每行、每列和每个3x3宫格是否包含1-9的所有数字。");
}

void MainWindow::updateTimerDisplay()
{
    m_timerLabel->setText(QString("时间: %1").arg(formatTime(m_elapsedTime)));
}

void MainWindow::showCongratulations()
{
    LevelProgress progress = GameManager::instance().getLevelProgress(m_currentLevelId);
    
    QString message = QString("恭喜！你成功完成了关卡 %1！\n\n").arg(m_currentLevelId);
    message += QString("用时: %1\n").arg(formatTime(m_elapsedTime));
    if (progress.bestTime == m_elapsedTime) {
        message += "🎉 新的最佳记录！\n";
    } else {
        message += QString("最佳记录: %1\n").arg(formatTime(progress.bestTime));
    }
    message += QString("尝试次数: %1\n\n").arg(progress.attempts);
    message += "是否继续下一关？";
    
    auto reply = QMessageBox::question(this, "恭喜通关", message, 
                                      QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        int nextLevel = m_currentLevelId + 1;
        if (nextLevel <= m_levelManager->getLevelCount()) {
            startGame(nextLevel);
        } else {
            QMessageBox::information(this, "通关", "恭喜你完成了所有关卡！");
            onShowMainMenu();
        }
    } else {
        onShowMainMenu();
    }
}

QString MainWindow::formatTime(int seconds) const
{
    int minutes = seconds / 60;
    int secs = seconds % 60;
    return QString("%1:%2").arg(minutes, 2, 10, QLatin1Char('0'))
                          .arg(secs, 2, 10, QLatin1Char('0'));
}
